/**
 * Copyright (c) 2015-2030 by Beijing Yanlight Co., Ltd.
 * All rights reserved.
 */
package com.yanlight.support.http;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * 
 * @author haolw
 * @time 2017/07/22
 */
public class RequestBuilder implements HttpConstants {
	private String url;
	private String method = POST;
	private String dataType = JSON;
	private String contentType = FORM;
	private Map<String, String> paramsMap;
	private Class<?> mapType = hashMap;

	public static RequestBuilder newBuilder() {
		return new RequestBuilder();
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getMethod() {
		return method;
	}

	public void setMethod(String method) {
		this.method = method;
	}

	public RequestBuilder get() {
		this.method = GET;
		return this;
	}

	public RequestBuilder post() {
		this.method = POST;
		return this;
	}

	public String getDataType() {
		return dataType;
	}

	public void setDataType(String dataType) {
		this.dataType = dataType;
	}

	public RequestBuilder dataJSON() {
		this.dataType = JSON;
		return this;
	}

	public RequestBuilder dataXML() {
		this.dataType = XML;
		return this;
	}

	public String getContentType() {
		return contentType;
	}

	public void setContentType(String contentType) {
		this.contentType = contentType;
	}

	public RequestBuilder contentFORM() {
		this.contentType = FORM;
		return this;
	}

	public RequestBuilder contentJSON() {
		this.contentType = JSON;
		return this;
	}

	public RequestBuilder contentXML() {
		this.contentType = XML;
		return this;
	}

	protected Map<String, String> getParamsMap() {
		return paramsMap;
	}

	private void constructorMap() {
		if (paramsMap == null) {
			if (hashMap.equals(mapType)) {
				paramsMap = new HashMap<String, String>(8);
			} else if (linkedHashMap.equals(mapType)) {
				paramsMap = new LinkedHashMap<String, String>(8);
			} else if (treeMap.equals(mapType)) {
				paramsMap = new TreeMap<String, String>();
			}
		}
	}

	public void addParams(Map<String, String> map) {
		constructorMap();
		paramsMap.putAll(map);
	}

	public void addParam(String key, String value) {
		constructorMap();
		paramsMap.put(key, value);
	}

	public void removeParam(String key) {
		if (paramsMap == null) {
			return;
		}
		paramsMap.remove(key);
	}

	public Class<?> getMapType() {
		return mapType;
	}

	public void setMapType(Class<?> mapType) {
		this.mapType = mapType;
	}

	public RequestBuilder linkedHashMap() {
		this.mapType = linkedHashMap;
		return this;
	}

	public RequestBuilder treeMap() {
		this.mapType = treeMap;
		return this;
	}

}
